package pkg0;

import java.util.LinkedList;
import java.util.Scanner;
import java.util.Stack;

public class Main {
	private static Stack<LinkedList<Integer>> group = new Stack<LinkedList<Integer>>();
	public static void main(String[] args) {
		reg(1);
		trace();
		reg(2);
		trace();
		reg(3);
		trace();
		reg(4);
		trace();
		rem(4);
		trace();
		
	}
	private static boolean reg(int x) {
		if(group.size() == 3) {
			if(group.peek().size() == 1){
				return false;
			}else{
				group.peek().add(Integer.valueOf(x));
			}
		}else if(group.size() == 2 || group.size() == 1) {
			if(group.peek().size() == 3){
				group.push(new LinkedList<Integer>());
			}
			group.peek().add(Integer.valueOf(x));
		}else{
			group.push(new LinkedList<Integer>());
			group.peek().add(Integer.valueOf(x));
		}
		return true;
	}
	
	private static boolean rem(int x) {
		if(group.size() == 0){
			return false;
		}else{
			if(group.peek().size() == 0){
				if(group.size() == 1){
					return false;
				}else{
					group.pop();
					int pos = group.peek().indexOf(Integer.valueOf(x));
					if(-1 != pos){
						group.peek().remove(pos);
					}else{
						return false;
					}
				}
			}else{
				int pos = group.peek().indexOf(Integer.valueOf(x));
				if(-1 != pos){
					group.peek().remove(pos);
				}else{
					return false;
				}
				if(group.peek().size() == 0) {
					group.pop();
				}
			}
		}
		
		return true;
	}
	
	private static void trace() {
		System.out.println(group.toString());
	}
}
